package nciae.db.conf;

import com.auth0.jwt.interfaces.Claim;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebFilter(filterName = "JwtFilter",urlPatterns = "/api/*")
public class JwtFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("filter 开始工作");
        final HttpServletRequest request = (HttpServletRequest) servletRequest;
        final HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 对预检请求放行
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            filterChain.doFilter(request, response);
            return;
        }

        // 排除登录接口的token验证
        String requestPath = request.getRequestURI();
        if (requestPath.equals("/api/login")) {
            filterChain.doFilter(request, response);
            return;
        }

        // 验证token
        final String token = request.getHeader("authorization");
        if (token == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("没有token！");
            return;
        }

        Map<String, Claim> userData = JwtUtil.verifyToken(token);
        if (userData == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("token66");
            return;
        }

        // 设置用户信息到request中
        Integer id = userData.get("id").asInt();
        String tel = userData.get("tel").asString();
        String name = userData.get("name").asString();
        String dep = userData.get("dep").asString();
        Integer classId = userData.get("classid").asInt();
        Integer projectId = userData.get("projectid").asInt();

        request.setAttribute("id", id);
        request.setAttribute("tel", tel);
        request.setAttribute("name", name);
        request.setAttribute("dep", dep);
        request.setAttribute("classid", classId.toString());
        request.setAttribute("projectid", projectId.toString());

        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }
}